import Snack from "./snack"
import Food from "./food"
import ScopePanel from "./scopePanel"

class GameControl {
    sanck: Snack;
    food: Food;
    scopePanel:ScopePanel;
    direction:string=""
    isLive: boolean = true;
    constructor() {
        this.sanck = new Snack()
        this.food = new Food()
        this.scopePanel = new ScopePanel()
        this.init()
    }

    init() {
        // 蛇需要根据我们按下的键盘上下键而位置发生改变
        document.addEventListener("keydown",this.keydownHandel.bind(this))
        this.run()
    }

    // 按键函数
    keydownHandel(event:KeyboardEvent) {
        // ArrowUp\ArrowDown\ArrowLeft\ArrowRight
        this.direction = event.key
    }

    // 蛇移动的函数
    run(){
        // 根据this.derection进行判断
        let Y = this.sanck.Y
        let X = this.sanck.X

        switch(this.direction) {
            case "ArrowUp":
            case "Up":
                Y -= 10;
                break;

            case "ArrowDown":
            case "Down":
                Y += 10
                break;
            
            case "ArrowLeft":
                case "Left":
                    X -= 10;
                    break;

            case "ArrowRight":
                case "Right":
                    X += 10;
                    break;
        }

        this.isLive && setTimeout(() => {
            this.run()
        }, 300 - (this.scopePanel.level -1)*30);
       if (this.checkEat(X,Y)) {
           this.food.change()
           this.scopePanel.addScope()
           this.sanck.addBody()
       }
        try {
            this.sanck.X = X;
            this.sanck.Y = Y;
        } catch (error) {
            this.isLive = false
            alert(error.message)
        }
        
    }

    // 检查蛇是否吃到食物
    checkEat(X:number,Y:number) {
        return X === this.food.X && Y === this.food.Y
    }
}

export default GameControl